package com.jx.driving.protocol.terminal.codec;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;

/**
 * word类型读取器
 * 
 * @author shenliuyang
 *
 *         2016年7月29日下午6:52:02
 */
public class WordFieldReaderWriter extends FieldReaderWriter {

	public WordFieldReaderWriter(Field field, int size, int order) {
		super(field, 2, order);
	}

	@Override
	public void read(InputStream in, Object to) throws IOException {
		ByteBuffer bb = ByteBuffer.allocate(4);
		bb.put((byte) 0);
		bb.put((byte) 0);
		bb.put((byte) in.read());
		bb.put((byte) in.read());
		bb.flip();
		wrtietoField(to, bb.getInt());
	}

	@Override
	public void write(OutputStream out, Object from) throws IOException {
		Number value = (Number) readFromField(from);
		if (value == null) {
			value = 0;
		}
		ByteBuffer bb = ByteBuffer.allocate(4);
		bb.putInt(value.intValue());
		byte[] b = bb.array();
		out.write(b[2]);
		out.write(b[3]);
	}
}